<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-09-05 14:16:12
 * @FilePath: \public-health-emergencies-fed:\新放射\新radiation-hygiene-fe\src\views\slide\task.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <el-dialog
    class="app-container"
    title="批量打印"
    :visible.sync="dialogVisible"
    v-dialogDrag="true"
    width="80%"
  >
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="单位名称" label-width="80px">
            <m-select
              v-model="queryParams.organizationName"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="organizationName"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批次" label-width="80px">
            <el-select
              v-model="queryParams.batchNum"
              placeholder="请选择批次"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in batchNumList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="佩戴时间">
            <el-date-picker
              v-model="queryParams.formDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              clearable
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row class="bloperation">
      <el-popconfirm
        title="是否批量打印？"
        :hide-icon="true"
        @confirm="handleAllPrint"
      >
        <el-button class="blbutton" slot="reference" type="primary" size="mini"
          >批量打印</el-button
        >
      </el-popconfirm>
      <el-popconfirm
        title="是否批量打印流转表？"
        :hide-icon="true"
        style="margin-left: 8px"
        @confirm="printTurnover"
      >
        <el-button class="blbutton" slot="reference" type="primary" size="mini"
          >打印流转表</el-button
        >
      </el-popconfirm>
    </el-row>
    <el-table
      ref="sendRefs"
      height="500"
      style="margin-bottom: 60px"
      v-loading="loading"
      :data="personalDosimeterList"
      @row-dblclick="(row) => openhandleDialog(row)"
      @selection-change="handleSelectionAChange"
    >
      <el-table-column type="selection" align="center" width="50" />
      <!-- <el-table-column label="委托单位名称" align="center" prop="entrustOrganizationName"/>
			<el-table-column label="人数" align="center" prop="personnelNum" :show-overflow-tooltip="true"/>
			<el-table-column label="年份" align="center" prop="year"/>
			<el-table-column label="批次" align="center" prop="batchNum"/> -->
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="合同编号" align="center" prop="agreementNumber" />
      <el-table-column
        label="委托单位"
        align="center"
        prop="entrustOrganizationName"
        :show-overflow-tooltip="true"
      />
      <el-table-column align="center" label="人数">
        <template slot-scope="{ row }">
          <el-button @click.native.prevent="openhandleDialog(row)" type="text">
            {{ row.personnelNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="联系人"
        align="center"
        prop="contactsName"
        width="120"
      />
      <el-table-column
        label="联系电话"
        align="center"
        prop="contactsMobile"
        width="150"
      />
      <el-table-column
        label="单位地址"
        align="center"
        prop="organizationAddress"
        width="150"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column label="检测人员" align="center" prop="personNum" width="150"/> -->
      <!-- <el-table-column label="录入时间" align="center" prop="createTime"/> -->
      <el-table-column label="佩戴起止时间" align="center" width="180">
        <template slot-scope="{ row }">
          {{
            parseTime(row.wearingBeginTime, "{y}/{m}/{d}") +
            " - " +
            parseTime(row.wearingEndTime, "{y}/{m}/{d}")
          }}
        </template>
      </el-table-column>
      <el-table-column label="年份" align="center" prop="year" width="100" />
      <el-table-column label="批次" align="center" prop="batchNum" width="60" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 待寄出人员列表 -->
    <el-dialog
      :title="bltitle"
      :visible.sync="dialogVisiblehandle"
      :close-on-click-modal="false"
      width="50%"
      class="bldialog"
      append-to-body
      v-dialogDrag="true"
    >
      <div class="bloperation">
        <el-button
          class="blbutton"
          type="primary"
          size="mini"
          @click="handlePrint"
          >批量打印</el-button
        >
      </div>
      <el-table
        class="handletabel"
        ref="tableData"
        v-loading="loadingHandle"
        :data="waitSendPeopleList"
        @selection-change="handleSelectionChange"
        height="364"
      >
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="姓名" align="center" prop="personnelName">
          <template slot-scope="{ row }">
            {{
              row.personnelName +
              `${
                row.dosageType == 1
                  ? "（内）"
                  : row.dosageType == 2
                  ? "（外）"
                  : ""
              }`
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="剂量计编号"
          align="center"
          prop="dosageNumber"
        />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="{ row }">
            {{ row.sex == 1 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column
          label="职业类别"
          align="center"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <dict-tag
              :value="scope.row.occupationalClassification"
              :options="dict.type.occupational_classification"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="穿戴开始"
          align="center"
          prop="wearingBeginTime"
        />
        <el-table-column
          label="穿戴结束"
          align="center"
          prop="wearingEndTime"
        />
      </el-table>

      <pagination
        style="margin-bottom: 5px"
        v-show="totalHandle > 0"
        :total="totalHandle"
        :page.sync="queryParamsHandle.pageNum"
        :limit.sync="queryParamsHandle.pageSize"
        @pagination="getHandleList"
      />
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  getWaitSendList,
  getWaitSendAllList,
  getWaitSendPersonnelList,
  getWaitSendPersonnelListByIds,
} from "@/api/slides/waitSend";
import { entrustOrganizationList } from "@/api/person/entrustOrganization";
import {
  printCode,
  handlePrintTurnoverRegister,
} from "@/utils/lodop/printFun.js";
import MSelect from "@/components/mSelect";

export default {
  name: "task",
  dicts: [
    "status_disable",
    "is_or_no",
    "sys_user_sex",
    "occupational_classification",
  ],
  components: { MSelect },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      rules: {
        entrustOrganizationId: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
        ],
      },
      batchNumList: [
        { label: 1, value: 1 },
        { label: 2, value: 2 },
        { label: 3, value: 3 },
        { label: 4, value: 4 },
      ],
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      // 外照射任务列表
      personalDosimeterList: [],
      // 办理弹框
      bltitle: "待寄出人员详情",
      dialogVisiblehandle: false,
      handleStatus: null,
      handleform: {},
      waitSendPeopleList: [],

      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      height: document.documentElement.clientHeight,
      loadingHandle: false,
      totalHandle: 0,
      // 办理的查询参数
      queryParamsHandle: {
        pageNum: 1,
        pageSize: 10,
        searchStr: "",
      },
      sendSelected: [],
      selected: [],
    };
  },
  created() {},
  methods: {
    openDialog() {
      this.dialogVisible = true;
      // 获取列表
      this.getList();
    },
    // 查看流程
    handleFlowRecord(row) {
      this.$refs.workFlow.openDialog(row);
    },
    // 获取外照射任务列表
    getList() {
      this.loading = true;
      this.queryParams.wearingBeginTime =
        this.queryParams.formDate && this.queryParams.formDate[0];
      this.queryParams.wearingEndTime =
        this.queryParams.formDate && this.queryParams.formDate[1];
      // delete this.queryParams.formDate;
      getWaitSendList(this.queryParams)
        .then((response) => {
          this.personalDosimeterList = response.rows || [];
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 打开办理对话框
    openhandleDialog(row) {
      // 获取未办理人员下拉框
      this.queryParamsHandle.dosimeterId = row.taskPersonalDosimeterId;
      this.selected = [];
      this.getHandleList();
    },
    getHandleList() {
      getWaitSendPersonnelList(this.queryParamsHandle).then((response) => {
        this.dialogVisiblehandle = true;
        this.waitSendPeopleList = response.rows || [];
        this.totalHandle = response.total;
      });
    },
    // 查询重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        tasksState: this.isPer ? "-4" : "-3",
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 更改打印勾选
    handleSelectionChange(selection) {
      this.selected = selection;
    },
    handleSelectionAChange(selection) {
      this.sendSelected = selection;
    },
    // 打印所有人员
    handleAllPrint() {
      // 查询所有
      if (this.sendSelected.length == 0) {
        this.printDataATable();
        return;
      }
      getWaitSendPersonnelListByIds({
        dosimeterIds: this.sendSelected.map((i) => i.taskPersonalDosimeterId),
      }).then((response) => {
        this.selected = response.data || [];
        this.handlePrint();
      });
    },
    // 打印流转表
    async printTurnover() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let printList = [];
      if (this.sendSelected.length == 0) {
        const query = {
          ...this.queryParams,
          wearingBeginTime:
            this.queryParams.formDate && this.queryParams.formDate[0],
          wearingEndTime:
            this.queryParams.formDate && this.queryParams.formDate[1],
          pageNum: null,
          pageSize: null,
        };
        let response = await getWaitSendAllList(query);
        printList = response.data;
      } else {
        printList = this.sendSelected;
      }
      printList.map(async (res) => {
        await handlePrintTurnoverRegister(
          res.taskPersonalDosimeterId,
          "2",
          true
        );
      });
      loading.close();
    },
    // 批量打印所有人员数据及流转表
    printDataATable() {
      const query = {
        ...this.queryParams,
        wearingBeginTime:
          this.queryParams.formDate && this.queryParams.formDate[0],
        wearingEndTime:
          this.queryParams.formDate && this.queryParams.formDate[1],
        pageNum: null,
        pageSize: null,
      };
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 查询所有
      getWaitSendAllList(query).then((response) => {
        const ids = response.data.map((i) => i.taskPersonalDosimeterId);
        getWaitSendPersonnelListByIds({
          dosimeterIds: ids,
        }).then(async (res) => {
          this.selected = res.data || [];
          await this.handlePrint();
          console.log(response.data);
          response.data.map(async (res) => {
            await handlePrintTurnoverRegister(
              res.taskPersonalDosimeterId,
              "2",
              true
            );
          });
          loading.close();
        });
      });
    },
    // 打印编号
    async handlePrint() {
      let printList = [];
      if (this.selected.length == 0) {
        this.$modal.msgWarning("请选择需要打印的人员");
        return;
      } else {
        printList = this.selected;
      }
      this.loading = true;
      await printCode(printList, "1", true);
      this.loading = false;
    },
    // 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell
    // 拼接后类似这样："1,0","1,1",
    dbclick(row, column) {
      if (this.handleStatus == "3") return;
      console.log("双击", row, column);
      this.currentCell = row.index + "," + column.index;
      // 这里必须要setTimeout，因为在点击的时候，input才刚被v-if显示出来，不然拿不到dom
      setTimeout(() => {
        // 双击后自动获得焦点
        if (this.$refs[row.index + "," + column.index]) {
          this.$refs[row.index + "," + column.index].focus();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .handletabel.el-table {
  margin-bottom: 60px;
  overflow: auto;
  .el-table__body-wrapper {
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
